package cn.itcast.quartz;

import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import cn.itcast.service.system.impl.UserServiceImpl;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 该类用于定时发送信息，例如生日邮件
 */

@Service
public class SendMessageJob implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private UserService userService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    //声明一个list集合用于存储当天生日的人
    public List<User> userList;

    /**
     * spring容器启动完成后调用此方法查询数据库中当天人的生日
     * @param event
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            //todo 执行一次  需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法
            /*SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        String nowDate = sdf.format(new Date());
        System.out.println(nowDate);*/
            String nowDate = "09-10";
            userList = userService.findByBirthday(nowDate);

            //在项目启动时给当天生日的人发送邮件，为了方便测试，写在项目启动时发送邮件，测试完成后
            //移植到sendBirthdayEmail()方法中运行
            for (User user : userList) {
                String userName = user.getUserName();
                String email = user.getEmail();
                String html = "<h1>这是一封生日邮件测试，无需回复</h1>";

                //将数据封装进map
                Map map = new HashMap();
                map.put("userName",userName);
                map.put("email",email);
                map.put("html",html);

                System.out.println("发送生日邮件成功");
                //发送邮件map到交换机
                amqpTemplate.convertAndSend("mail.birthday",map);  //map -- json -- byte[]发送
            }
        }
    }


    //发送生日邮件
    public void sendBirthdayEmail(){

    }
}
